<% 
var headContent = {
%>
<link rel="stylesheet" type="text/css" href="${base}/template/admin/css/jquery.contextmenu.css">
<%
};
%>

<%layout("/common/_layout.html",{head:headContent}){ %>
<%#ajax userTable:{%>
    <div class="am-margin">
        <!-- 左边展示表名 -->
	    <div class="am-u-sm-2 am-u-md-2">
	       <div class="am-input-group am-input-group-primary am-input-group-sm">
                <input type="text" id="tableName" class="am-form-field">
                <span class="am-input-group-btn">
                    <button class="am-btn am-btn-primary" type="button" onclick="javascript:initTables();"><span class="am-icon-refresh"></span></button>
                </span>
            </div>
	       
	       <ul id="tables" class="am-scrollable-vertical" style="border:1px solid;list-style:none;height:500px;"></ul>
	    </div>
	
	
	    <!-- SQL窗口的tab -->
	    <div id="sqltab" class="am-tabs am-u-sm-10 am-u-md-10" data-am-tabs>
			<ul class="am-tabs-nav am-nav am-nav-tabs">
			  <li class="am-active"><a href="#tab1">SQL</a></li>
			</ul>
	        <div class="am-tabs-bd">
	            <div class="am-tab-panel am-fade am-in am-active" id="tab1">
	                <div class="am-btn-toolbar">
	                    <div class="am-btn-group">
							<button type="button" class="am-btn am-btn-primary am-radius am-margin-right-sm" onclick="javascript:sqlexecute();">执行</button>
							<button type="button" class="am-btn am-btn-primary am-radius am-margin-right-sm" onclick="javascript:clearsqlstatement();">清空</button>
	                    </div>
	                </div>
	                <textarea rows="4" cols="100" id="sql-statement" placeholder="请输入合法的SQL语句"></textarea>
		            <div id="tab" class="am-tabs am-margin-top-sm" data-am-tabs>
						<ul class="am-tabs-nav am-nav am-nav-tabs">
							<li class="am-active"><a href="#tab11">执行结果</a></li>
							<li><a href="#tab22">结果集</a></li>
						</ul>
		                <div class="am-tabs-bd">
		                    <div class="am-tab-panel am-fade am-in am-active" id="tab11">
		                        <div class="am-g am-form-group am-margin-top">
		                            <div class="am-u-sm-12 am-u-md-12">
		                                <div class="" id="info"></div>
		                            </div>
		                        </div>
		                    </div>
		                    <div class="am-tab-panel am-fade" id="tab22">
		                        <div class="am-scrollable-horizontal am-scrollable-vertical">
		                            <table id="result" class="am-table am-table-bordered am-table-striped am-text-nowrap am-table-hover am-hide" cellspacing="0" border="1" rules="all" style="user-select:auto;-webkit-user-select: auto;-moz-user-select:auto;-ms-user-select:auto;">
		                                <thead><tr></tr></thead>
									    <tbody></tbody>
									</table>
		                        </div>
		                    </div>
		                </div>
		            </div> 
	            </div>
	            
	            
	            <div class="am-tab-panel am-fade" id="tab2">
	               <div class="am-btn-toolbar">
                        <div class="am-btn-group">
                           <input type="password" class="am-form-field" id="password" placeholder="输入修改权限的密码">
					       <button type="button" class="am-btn am-btn-primary am-radius am-margin-right-sm" onclick="javascript:sqlpermission();">打开修改SQL权限</button>
					       <button type="button" class="am-btn am-btn-primary am-radius" onclick="javascript:unsqlpermission();">去掉修改SQL权限</button>
                        </div>
                    </div>
                </div>
                
                
                <div class="am-tab-panel am-fade" id="tab3">
                   <div class="am-btn-toolbar">
                        <div class="am-btn-group">
                           <button type="button" class="am-btn am-btn-primary am-radius am-margin-right-sm" onclick="javascript:sqlrefresh();">刷新</button>
                           <button type="button" class="am-btn am-btn-primary am-radius am-margin-right-sm" onclick="javascript:sqlclean();">清除记录</button>
                        </div>
                    </div>
                    
                    <div class="" id="dumpmsg"></div>
                    <div class="am-scrollable-horizontal am-scrollable-vertical">
                        <table id="dumpRecord" class="am-table am-table-bordered am-table-striped am-text-nowrap am-table-hover" cellspacing="0" border="1" rules="all" style="user-select:auto;-webkit-user-select: auto;-moz-user-select:auto;-ms-user-select:auto;">
                            <thead><tr></tr></thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
                
                <!--
                <div class="am-tab-panel am-fade" id="tab4">
                   <div class="am-g am-form-group am-margin-top">
                      <div class="am-u-sm-12 am-u-md-12">
                        <div class="am-form-file am-text-xs">
                          <button type="button" class="am-btn am-btn-primary am-btn-sm">
                            <i class="am-icon-cloud-upload"></i> 选择要SQL文件上传
                          </button>
                          <input id="fileupload" type="file" name="files[]" multiple>
                        </div>
                        先去掉-- The global progress bar 先去掉--
                        <div id="progress-area" class="am-margin-top-sm am-hide">
                          <div id="progress-text" class="am-text-xs am-text-right"></div>
                          <div class="am-progress am-progress-striped am-progress-sm am-active ">
                            <div class="am-progress-bar am-progress-bar-secondary"  style="width: 100%"></div>
                          </div>
                          先去掉--
                          <div id="progress" class="am-progress am-progress-xs">
                            <div class="am-progress-bar" style="width: 0%"></div>
                          </div>
                          先去掉--
                        </div>
                      </div>
                    </div>
                </div>
                -->
                
                
	        </div>
	    </div>
    </div>
    
    
  <script type="text/javascript" src="${base}/template/website/js/app.js"></script>
  <script type="text/javascript" src="${base}/template/admin/js/table_resize.js"></script>
  <script type="text/javascript" src="${base}/template/admin/js/jquery.contextmenu.js"></script>
    <!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
    <script type="text/javascript" src="${base}/template/jQuery-File-Upload/js/vendor/jquery.ui.widget.js"></script>
    <!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
    <script type="text/javascript" src="${base}/template/jQuery-File-Upload/js/jquery.iframe-transport.js"></script>
    <!-- The basic File Upload plugin -->
    <script type="text/javascript" src="${base}/template/jQuery-File-Upload/js/jquery.fileupload.js"></script>
  <script type="text/javascript">
      //Html编码获取Html转义实体
      function htmlEncode(value){
        return $('<div/>').text(value).html();
      }
      //Html解码获取Html实体
      function htmlDecode(value){
        return $('<div/>').html(value).text();
      }
      
  
      function html2Escape(sHtml) { //Html转义
         //console.info(sHtml);
         if(null==sHtml){return "null";}
         if(!isNaN(sHtml)){return sHtml+"";}
         return sHtml.replace(/[<>]/g,function(c){
            return {"<":"&lt;",">":"&gt;"}[c];
         }); 
      } 
      function sqlclean(){
          $("#dumpmsg").html("");
          var params={};
          var reqUrl = "${base}/sql/sqlClean";
          sendPostAjax(params,reqUrl,function(data){
                var $dumpRecord = $("#dumpRecord");
                $dumpRecord.addClass("am-hide");
                var $body = $dumpRecord.children("tbody");
                $body.html("");
                alert(data);
          });
      }
      
      function sqlrefresh(){
          $("#dumpmsg").html("");
          var params={};
          var reqUrl = "${base}/sql/sqlRefresh";
          sendPostAjax(params,reqUrl,function(data){
                var $dumpRecord = $("#dumpRecord");
                $dumpRecord.removeClass("am-hide");
                var $headtr = $dumpRecord.children("thead").children("tr");
                var $body = $dumpRecord.children("tbody");
                $headtr.html("");
                $body.html("");
                if(data.length>0){
                  var object = data[0];
                  var arr = new Array();
                  for(var key in object){//名称
                      arr.push(key);//为了保证顺序
                      $headtr.append("<th style='max-width:200px;' class='am-text-truncate'>"+key+"</th>");//头增加一列
                  }  
                  for(var i=0;i<data.length;i++){  //循环所有列
                      var object = data[i];
                      var aline = "";
                      var id = object["id"];
                      for(var j=0;j<arr.length;j++){
                          var content = html2Escape(object[arr[j]]);
                          if("filename"==arr[j]){
                            aline+="<td style='max-width:200px;' class='am-text-truncate' title='"+content+"'><a href='${base}/sql/download?id="+id+"'>"+content+"</a></td>";
                          }else{
                            aline+="<td style='max-width:200px;' class='am-text-truncate' title='"+content+"'>"+content+"</td>";
                          }
                          
                      }
                      $body.append("<tr>"+aline+"</tr>");//体增加一列
                  }
              }
          });
      }
      
      function sqlpermission(){
          var params={"password":$("#password").val()};
          var reqUrl = "${base}/sql/sqlPermission";
          sendPostAjax(params,reqUrl,function(data){
                alert(data);
          });
      }
      function unsqlpermission(){
          var params={"password":$("#password").val()};
          var reqUrl = "${base}/sql/unSqlPermission";
          sendPostAjax(params,reqUrl,function(data){
                alert(data);
          });
      }
      
      function showStatement(data){
          $("#sql-statement").val(data);
      }
      
      function sqlformart(){
          var params={"sql-statement":$("#sql-statement").val()};
          var reqUrl = "${base}/sql/sqlFormat";
          sendPostAjax(params,reqUrl,showStatement);
      }
      function clearsqlstatement(){
          //console.info($("#sql-statement").val());
          $("#sql-statement").val("");
      }
      
      function handleResult(data){
          
          $("#info").html("您执行的sql语句为：<span class='am-text-lg am-text-danger'>"+data.sqlStatement+"</span><br/>"+data.resultDesp);
          var $result = $("#result");
          var $headtr = $result.children("thead").children("tr");
          var $body = $result.children("tbody");
          $headtr.html("");
          $body.html("");
          $result.addClass("am-hide");
          if(data.result == 0){//select语句
              $("#sqltab").tabs('open', 0);//切换到SQL
              $("#tab").tabs('open', 1);//切换到结果集
              var datamap = data.datamap;//[{},{}]
              $result.removeClass("am-hide");
              
              if(datamap.length>0){
                  var object = datamap[0];
                  var arr = new Array();
                  for(var key in object){//名称
                      arr.push(key);//为了保证顺序
                      $headtr.append("<th style='max-width:200px;' class='am-text-truncate'>"+key+"</th>");//头增加一列
                  }  
                  for(var i=0;i<datamap.length;i++){  //循环所有列
                      var object = datamap[i];
                      var aline = "";
                      for(var j=0;j<arr.length;j++){
                          var content = html2Escape(object[arr[j]]);
                          aline+="<td style='max-width:200px;' class='am-text-truncate' title='"+content+"'>"+content+"</td>";
                      }
                      $body.append("<tr>"+aline+"</tr>");//体增加一列
                  }
              }
          }
          $("#result").tableresize();
      }
      
      function sqlexecute(){
          var params={"sql-statement":$("#sql-statement").val()};//
          //console.info(params);
          $.ajax({
                type: "post",
                url: "${base}/sql/execute",
                data: params,
                dataType: "json",
                success: function(data) {
                    //console.info(data);
                    if(data.ResultCode!=1000){
                      $("#info").html(data.ResultCode+":"+data.Message);
                      return ;
                    }
                    handleResult(data.Data);
                }
          });
      }
      //展示表数据
      var insertSelect = function(tableName){
         $("#sql-statement").val("select * from "+tableName+" limit 0,10");
         $("#tableName").val(tableName);
         sqlexecute();
      }
      //展示表结构
      function showtableconstruct(tableName){
          var params={"tableName":tableName};
          var reqUrl = "${base}/sql/showTableConstruct";
          sendPostAjax(params,reqUrl,function(data){
                $("#sqltab").tabs('open', 0);//切换到sql
                handleResult(data);
          });
      }
      //下载SQL
      var dumpsql = function(tableName){
         var params={"tableName":tableName};
          var reqUrl = "${base}/sql/dumpSQL";
          sendPostAjax(params,reqUrl,function(data){
                $("#sqltab").tabs('open', 2);//切换到导出数据
                sqlrefresh();
                $("#dumpmsg").html(data);
          });
      }
      
      function showTables(data){
          $("#tables").html("");
          for(var i=0;i<data.length;i++){
              var table = data[i];
              for(var j in table){
                 //j=Tables_in_cqdzg,table[j]就是表名
                 //console.info(j+"===="+table[j]); 
                 //$("#tables").append("<li><a title='单击展示表数据，双击展示表结构' href='javascript:void(0);' ondblclick='javascript:showtableconstruct(\""+table[j]+"\");' onclick='javascript:insertSelect(\""+table[j]+"\");'>"+table[j]+"</a></li>");
                 var tableName=table[j];
                 $("#tables").append("<li><a title='右键弹出菜单操作' style='list-style-type:none;margin-left:-20px;' href='javascript:void(0);' id='"+tableName+"' >"+tableName+"</a></li>");
                 //给每个表绑定右击事件
                 $('#tables #'+tableName).contextPopup({
                  //title: '表操作',
                  items: [
                    {label:'查看表结构', tableName:tableName,icon:'${base}/template/admin/images/structure.png',action:function() {showtableconstruct(this.tableName); } },
                    {label:'查看表数据', tableName:tableName,icon:'${base}/template/admin/images/data.png',action:function() {insertSelect(this.tableName); } }
                  ]
        
                });
              }
          }
      }
          
      function initTables(){
          var params = {"tableName":$("#tableName").val()};
          var reqUrl = "${base}/sql/tables";
          sendPostAjax(params,reqUrl,showTables);
      }
      
      $(function(){
          initTables();
          
          /*附件上传：begin*/
          var jqXHR = $('#fileupload').fileupload({
              url: "${base}/sql/uploadSQL/",
              dataType: 'json',
              start: function (e) {
              },
              done: function (e, data) {
                if(jo.status == 'success'){
                  alert(jo.message);
                }
              },
              progressall: function (e, data) {
              },
              error: function (jqXHR, textStatus, errorThrown) {
              },
              fail: function (jqXHR, textStatus) {        
              }
         });
         /*附件上传：end*/
          
      });
      
      /**
     	 封装ajax请求
      */
      var sendPostAjax = function(params,reqUrl,successFun,loadingBarId){
        console.log("request url = "+reqUrl);
        console.log("request params = "+JSON.stringify(params));
        $.ajax({
          type: "post",
          url: reqUrl,
          data: params,
          dataType: "json",
          success: function(data) {
            console.log(data);
            if(loadingBarId){
              $("#"+loadingBarId).addClass("am-hide");
            }
            if(!data){
              alert("获取数据失败！");
              return;
            }
            if(data.ResultCode != 1000){
              alert(data.Message);
              console.log("接口返回数据错误：errorCode = "+data.ResultCode);
              return;
            }
             var returnData = data.Data;
            // if(!returnData || $.isEmptyObject(returnData)){
            //   alert("获取的数据为空！");
            //   return;
            // }

            successFun(returnData);
          },
          error : function(textStatus) {
            if(loadingBarId){
              $("#"+loadingBarId).addClass("am-hide");
            }
            alert("请求服务器出错，请联系管理员！");
            console.log("request error");
          }
        });
      };

    </script>
<%}%>
<%}%> 